package com.flutter.flutter_comm100

import android.app.Activity
import android.content.Intent
import android.view.View
import android.webkit.CookieManager
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.widget.ProgressBar
import android.widget.RelativeLayout
import com.comm100.livechat.VisitorClientInterface
import com.comm100.livechat.core.VisitorClientCore
import com.comm100.livechat.view.ChatWindowWebView
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

class ClientComm100View(
    activity: Activity,
    messenger: BinaryMessenger,
    viewId: Int,
    args: Map<String, Any>?,
) : PlatformView, MethodChannel.MethodCallHandler {
    private val mChatWindow: ChatWindowWebView by lazy { ChatWindowWebView(activity) }
    private var methodChannel: MethodChannel? = null

    private var baseLayout: RelativeLayout

    init {
        baseLayout = RelativeLayout(activity)
        args?.let {
            val url = it["url"] as String?
            VisitorClientInterface.setChatUrl(url)
            mChatWindow.loadUrl(VisitorClientCore.getInstance().chatUrl)
            CookieManager.getInstance().setAcceptCookie(true)
            methodChannel = MethodChannel(messenger,
                "flutter_comm100_$viewId")
            methodChannel?.setMethodCallHandler(this)

            baseLayout.addView(mChatWindow)
            val progressBar = ProgressBar(activity)
            val scale: Float = activity.resources.displayMetrics.density
            val dp50 = (30 * scale + 0.5f).toInt()
            val layoutParams = RelativeLayout.LayoutParams(dp50,
                dp50)
            layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT)
            progressBar.layoutParams = layoutParams
            baseLayout.addView(progressBar)

            mChatWindow.webChromeClient = object : WebChromeClient() {
                override fun onCloseWindow(window: WebView?) {
                    super.onCloseWindow(window)
                    methodChannel?.invokeMethod("onClose", null)
                }

                override fun onProgressChanged(view: WebView?, newProgress: Int) {
                    super.onProgressChanged(view, newProgress)
                    if (newProgress >= 90) {
                        progressBar.visibility = View.GONE
                    }
                }
            }
        }
    }

    override fun getView(): View {
        return baseLayout
    }

    override fun dispose() {
        mChatWindow.destroy()
        methodChannel?.setMethodCallHandler(null)
    }

    fun activityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean {
        mChatWindow.onActivityResult(requestCode, resultCode, data)
        return false
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {

    }
}